<script setup>
import { computed, reactive } from 'vue';

const state = reactive({
  list: [
    { id: 1, name: '吃饭', flag: true },
    { id: 2, name: '睡觉', flag: false },
    { id: 3, name: '打豆豆', flag: true },
  ],
  todoName: ''
});

/**
 * 删除
 * @param {number} id
 */
const delTodo = (id) => {
  /* const idx = state.list.findIndex(item => item.id === id)
  state.list.splice(idx, 1) */
  // filter => 保留
  state.list = state.list.filter(item => item.id !== id)
}

const addItem = () => {
  // 把 state.todoName 加工成 对象
  state.list.unshift({ id: Date.now(), name: state.todoName, flag: false })
  state.todoName = ''
}

// 剩余数量
const leftCounts = computed(() => {
  return state.list.filter(item => item.flag === false).length
})
// 是否显示底部
const isShowFooter = computed(() => {
  return state.list.length !== 0
})
// 是否显示清空已完成按钮
const isShowClear = computed(() => {
  return state.list.some(item => item.flag === true)
})
// 清空已完成 => 保留未完成
const clearCompleted = () => {
  state.list = state.list.filter(item => item.flag === false)
};
</script>
<template>
  <section class="todoapp">
    <header class="header">
      <h1>todos</h1>
      <!-- 输入框 -->
      <input class="new-todo" placeholder="What needs to be done?" autofocus v-model="state.todoName" @keyup.enter="addItem" />
    </header>

    <section class="main">
      <!-- 全选按钮 -->
      <input id="toggle-all" class="toggle-all" type="checkbox" />
      <label for="toggle-all">Mark all as complete</label>
      <ul class="todo-list">
        <!-- 给 li 加 completed 就可以有选中的样式 -->
        <li :class="{ completed: item.flag }" v-for="item in state.list" :key="item.id">
          <div class="view">
            <!-- 给 input 加 checked 就可以选中 -->
            <input class="toggle" type="checkbox" v-model="item.flag" />
            <label>{{item.name}}</label>
            <!-- 删除按钮 -->
            <button class="destroy" @click="delTodo(item.id)"></button>
          </div>
          <input class="edit" value="Create a TodoMVC template" />
        </li>
      
      </ul>
    </section>

    <footer class="footer" v-if="isShowFooter">
      <!-- 剩余数量 -->
      <span class="todo-count"><strong>{{leftCounts}}</strong> item left</span>
      <ul class="filters">
        <li>
          <a class="selected" href="#/">All</a>
        </li>
        <li>
          <a href="#/active">Active</a>
        </li>
        <li>
          <a href="#/completed">Completed</a>
        </li>
      </ul>
      <!-- 清空已完成 -->
      <button class="clear-completed" v-if="isShowClear" @click="clearCompleted">Clear completed</button>
    </footer>
  </section>
</template>